//
//  GQFriendController.m
//  GuQu
//
//  Created by HELIUM STAR on 15/5/7.
//  Copyright (c) 2015年 HELIUM STAR. All rights reserved.
//

#import "GQFriendController.h"
#import "GQFriendView.h"
#import <AddressBook/AddressBook.h>
#import "GQProfileContact.h"
#import "GQRegisterContactController.h"
#import "GQRegisterContactParam.h"
#import "GQRegisterTool.h"
#import "GQRegisterUserInfo.h"
#import "GQRegisterContactResult.h"
#import "GQRegisterUserInContancts.h"

@interface GQFriendController () <UIAlertViewDelegate>

@property (strong, nonatomic) NSArray *imageArr;
@property (strong, nonatomic) NSArray *nameArr;
@property (strong, nonatomic) NSArray *colorArr;
@property (assign, nonatomic) NSInteger count;

@end

@implementation GQFriendController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"好友推荐";
    
    UIButton *btn = [[UIButton alloc] init];
    btn.frame = CGRectMake(0, 0, 50, 20);
    [btn setTitle:@"跳过" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn.titleLabel.textAlignment = NSTextAlignmentRight;
    btn.titleLabel.font = [UIFont systemFontOfSize:14];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    GQFriendView *friendViewOne = [[GQFriendView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 350)];
    GQFriendView *friendViewTwo = [[GQFriendView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(friendViewOne.frame), kScreenWidth, 350)];

    scrollView.contentSize = CGSizeMake(kScreenWidth, CGRectGetMaxY(friendViewTwo.frame) + 10);
    scrollView.showsVerticalScrollIndicator = NO;
    [scrollView addSubview:friendViewOne];
    [scrollView addSubview:friendViewTwo];
    [self.view addSubview:scrollView];
    
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"古趣想访问你的通讯录" delegate:self cancelButtonTitle:@"不允许" otherButtonTitles:@"好", nil];
    [alertView show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [self getAddressBook];
    }
}

- (void)getAddressBook
{
    ABAuthorizationStatus status = ABAddressBookGetAuthorizationStatus();
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
    NSLog(@"%ld", status);
    if (status == kABAuthorizationStatusNotDetermined) {
        ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
            if (granted) {
//                GQProfileContactContrller *GQPCC = [[GQProfileContactContrller alloc] init];
//                [self.navigationController pushViewController:GQPCC animated:YES];
                NSLog(@"用户授权成功");
            } else {
                NSLog(@"用户授权失败");
            }
        });
    }
    
    if (status == kABAuthorizationStatusAuthorized) {
        
        NSMutableArray *phoneArrM = [NSMutableArray array];
        CFArrayRef peopelArray = ABAddressBookCopyArrayOfAllPeople(addressBook);
        CFIndex peopleCount = CFArrayGetCount(peopelArray);
        
        NSMutableArray *phoneNumArrM = [NSMutableArray array];
        
        for (CFIndex i = 0; i < peopleCount; i++) {
            //获取具体的联系人
            GQProfileContact *GQPC = [[GQProfileContact alloc] init];
            ABRecordRef person = CFArrayGetValueAtIndex(peopelArray, i);
            
            //获取具体的联系人
            NSString *firstName = (__bridge_transfer NSString *) ABRecordCopyValue(person, kABPersonFirstNameProperty);
            NSString *lastName = (__bridge_transfer NSString *) ABRecordCopyValue(person, kABPersonLastNameProperty);
            
            NSString *name = nil;
            if (!firstName && !lastName) {
                name = @"未命名";
            }else if (!firstName) {
                name = lastName;
            }else if(!lastName){
                name = firstName;
            }else{
                name = [NSString stringWithFormat:@"%@%@", lastName, firstName];
            }
            GQPC.name = name;
            
            //获取联系人的姓名
            ABMultiValueRef phones = ABRecordCopyValue(person, kABPersonPhoneProperty);
            CFIndex phoneCount = ABMultiValueGetCount(phones);
            NSMutableArray *arrM = [NSMutableArray array];
            for (CFIndex i = 0; i < phoneCount; i++) {
                NSString *phoneValue = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(phones, i);
                phoneValue = [phoneValue stringByReplacingOccurrencesOfString:@"-" withString:@""];
                phoneValue = [phoneValue stringByReplacingOccurrencesOfString:@"(" withString:@""];
                phoneValue = [phoneValue stringByReplacingOccurrencesOfString:@")" withString:@""];
                phoneValue = [phoneValue stringByReplacingOccurrencesOfString:@" " withString:@""];
                phoneValue = [phoneValue stringByReplacingOccurrencesOfString:@"·" withString:@""];
                [arrM addObject:phoneValue];
            }
            
            GQPC.phoneNums = arrM;
            [phoneNumArrM addObject:arrM[0]];
            
            CFRelease(phones);
            
            if (ABPersonHasImageData(person)) {
                NSData *imageData = (__bridge_transfer NSData *)ABPersonCopyImageDataWithFormat(person, kABPersonImageFormatThumbnail);
                UIImage *image = [UIImage imageWithData:imageData];
                GQPC.image = image;
                GQPC.icon = false;
                
            }else{
                UIImage *image = [UIImage imageNamed:self.colorArr[_count % 3]];
                GQPC.image = image;
                GQPC.icon = true;
                _count++;
            }
            
            GQPC.star = @"0";
            [phoneArrM addObject:GQPC];
        }
        
        CFRelease(addressBook);
        CFRelease(peopelArray);
    
        GQRegisterContactParam *contactParam = [[GQRegisterContactParam alloc] init];
        contactParam.tels = [phoneNumArrM componentsJoinedByString:@","];
//        GQRegisterUserInfo *userInfo = [[GQRegisterUserInfo alloc] init];
//        contactParam.userId = userInfo.userId;
        contactParam.userId = @"1";
        
        [GQRegisterTool registerGetContactInfo:contactParam success:^(NSArray *result) {
          
            for (GQRegisterUserInContancts *contact in result) {
                for (int i = 0;i < phoneArrM.count; i++) {
                    GQProfileContact *GQPC = phoneArrM[i];
                    NSMutableArray *phoneArr = GQPC.phoneNums;
                    if ([contact.mobile isEqualToString:phoneArr[0]]) {
                        [phoneArrM insertObject:GQPC atIndex:0];
                        [phoneArrM removeObjectAtIndex:i+1];
                        GQPC.star = contact.isStar;
                        GQPC.reg = YES;
                    }
                    
                }
            }
            
            for (int i = 0;i < phoneArrM.count; i++) {
                GQProfileContact *GQPC = phoneArrM[i];
                if ([GQPC.isStar isEqualToString:@"1"]) {
                    [phoneArrM insertObject:GQPC atIndex:0];
                    [phoneArrM removeObjectAtIndex:i+1];
                }
            }
            
            GQRegisterContactController *GQRCC = [[GQRegisterContactController alloc] init];
            GQRCC.phoneArr = phoneArrM;
            
            [self.navigationController pushViewController:GQRCC animated:YES];
            
        } failure:^(NSError *error) {
            
        }];
    }
    
    if (status == kABAuthorizationStatusDenied) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"通讯录获取失败 请在设置中授权给本程序" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
    }
}

- (NSArray *)colorArr
{
    if (_colorArr == nil) {
        _colorArr = [NSArray arrayWithObjects:@"profile_icon1", @"profile_icon2", @"profile_icon3", nil];
    }
    return _colorArr;
}


@end
